/*
 * @Author: Logan.Li
 * @Gitee: https://gitee.com/attacker
 * @email: admin@attacker.club
 * @Date: 2025-02-22 21:58:36
 * @LastEditTime: 2025-02-23 00:31:53
 * @Description: 
 */
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useRouterStore } from './router';
import { login, getUserInfo } from '../api/user/userinfo';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: sessionStorage.getItem('token'),
    userInfo: null,
    permissions: []
  }),
  actions: {
    async login(loginForm) {
      console.log('开始执行登录请求，参数：', loginForm);
      try {
        const response = await login(loginForm);
        console.log('登录请求响应：', response);
        
        if (response.data && response.data.token) {
          console.log('设置token到sessionStorage：', response.data.token.substring(0, 30) + '...');
          sessionStorage.setItem('token', response.data.token);
          this.token = response.data.token;
        } else {
          console.error('登录响应中没有token：', response);
        }
        return response;
      } catch (error) {
        console.error('登录请求失败：', error);
        throw error;
      }
    },
    async getUserInfo() {
      console.log('开始获取用户信息，当前token：', this.token.substring(0, 30) + '...');
      try {
        const response = await getUserInfo();
        console.log('获取用户信息响应：', response);
        
        if (response.data) {
          this.userInfo = response.data;
          this.permissions = response.data.permissions || [];
          console.log('用户信息和权限已更新：', {
            userInfo: this.userInfo,
            permissions: this.permissions
          });
        } else {
          console.error('获取用户信息响应异常：', response);
          throw new Error('获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息请求失败：', error);
        throw error;
      }
    }
  }
});